﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using CardsServer.Tools;
namespace CardsServer.WCF
{
    /// <summary>
    /// This class represent mail server.
    /// </summary>
    public class Server : IDisposable
    {
        private string m_StartupPath = "";
        private bool m_Running = false;
        private Timer m_pSettingsTimer = null;
        private DateTime m_ServersFileDate = DateTime.MinValue;
        private bool m_autoRunVS = Convert.ToBoolean(MyConfig.getAppValue("isAutoRunVS"));
        //private MonitoringServer    m_pManagementServer = null;
        private DateTime m_StartTime;
        public List<VirtualServer> m_pVirtualServers = null;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public Server()
        {
            m_pSettingsTimer = new Timer(30000);
            m_pSettingsTimer.Elapsed += new ElapsedEventHandler(m_pSettingsTimer_Elapsed);
            m_pSettingsTimer.Enabled = true;
            m_pVirtualServers = new List<VirtualServer>();

            // Add unhandled exception handler
            System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            // Get startup path
            m_StartupPath = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + "\\";
            LoadVirtualServers();
        }

        void m_pSettingsTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //if (DateTime.Now > new DateTime(2012, 10, 01, 0, 0, 0))
            //{
            //    foreach (VirtualServer vs in m_pVirtualServers)
            //    {
            //        vs.Enabled = false;
            //    }
            //    MyLog.writeErrorToLog("试用版本已到期，请联系开发商获得正式版本!");
            //}
        }





        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Error.DumpError((Exception)e.ExceptionObject, new System.Diagnostics.StackTrace());
        }


        #region method Start

        /// <summary>
        /// Starts mail server.
        /// </summary>
        public void Start()
        {
            // Server is already running, so do nothing.
            if (m_Running)
            {
                return;
            }


            //m_pSettingsTimer.Enabled = true;
            if (m_autoRunVS)
            {
                foreach (VirtualServer server in m_pVirtualServers)
                {
                    server.Enabled = true;
                }
            }

            // Start management server
            //m_pManagementServer = new MonitoringServer(this);
            //m_pManagementServer.StartServer();

            m_Running = true;
            m_StartTime = DateTime.Now;
        }

        #endregion

        #region method Dispose

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        public void Dispose()
        {
            Stop();
        }

        #endregion



        /// <summary>
        /// Loads virtual server from xml file.
        /// </summary>
        internal void LoadVirtualServers()
        {
            try
            {
                string file = AppDomain.CurrentDomain.BaseDirectory + @"\services.xml";

                try
                {
                    serviceconfig.ConfiguredServices services = serviceconfig.ConfiguredServices.LoadFromFile(file);


                    foreach (serviceconfig.ConfiguredService svc in services.Services)
                    {
                        string[] type = svc.Type.Split(',');
                        Guid id = new Guid(type[4]);
                        Type svcType = Type.GetType(type[0]);
                        Type svcIType = Type.GetType(type[1]);
                        string name = type[3];
                        string Uri = type[2];
                        string bindingtype = type[5];
                        if (svcType == null)
                        {

                            continue;

                        }


                        if (m_pVirtualServers.Count(p => p.Address == Uri) == 0)
                        {
                            VirtualServer vs = new VirtualServer(this, id, name, svcType, svcIType, Uri,bindingtype);
                            m_pVirtualServers.Add(vs);
                        }

                    }


                }
                catch (Exception ex)
                {
                    MyLog.writeErrorToLog(ex.Message);
                }

            }
            catch (Exception x)
            {
                Error.DumpError(x, new System.Diagnostics.StackTrace());
            }
        }

        #region method Stop

        /// <summary>
        /// Stops mail server.
        /// </summary>
        public void Stop()
        {
            // Server isn't running, so do nothing.
            if (!m_Running)
            {
                return;
            }



            // Kill all running virtual servers
            foreach (VirtualServer server in m_pVirtualServers)
            {
                server.Stop();
            }
            m_pVirtualServers.Clear();

            // Kill management server
            //m_pManagementServer.Dispose();
            //m_pManagementServer = null;

            m_Running = false;

            // Logging stuff
            //Logger.WriteLog(m_StartupPath + "Logs\\Server\\server.log", "//---- Server stopped " + DateTime.Now);
        }

        #endregion
    }
}
